package com.jy.horny.base.adpater

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import com.jy.horny.base.bindLifecycle
import com.jy.horny.base.observeOnMain
import com.jy.horny.base.subscribeOnIO
import com.jy.horny.dialog.LoadingDialog
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 通常作为网络请求结果的接受者
 * 构造方法中的 context 对象用于创建 loadingDialog
 * 构造方法中的 lifecycleOwner 用于将该请求绑定生命周期. 如果不需要和ui关联则可以直接使用 ObserverAdapter
 *
 * 当请求在800毫秒内还没有完成的请求下.LoadingDialog将显示在界面上.
 */
open class SimpleObserverAdapter<T>(private val context: Context, owner: LifecycleOwner) : ObserverAdapter<T>() {
    private var displayTask: Disposable? = null
    private var loadingDialog: LoadingDialog? = null

    init {
        bindLifecycle(owner)
    }

    override fun onComplete() {
        release()
    }

    override fun onError(e: Throwable) {
        super.onError(e)
        release()
    }

    // also invoke when context onStop
    fun release() {
        displayTask?.dispose()
        loadingDialog?.dismiss()
        loadingDialog = null
    }

    override fun onStart() {

        displayTask = Observable.timer(800, TimeUnit.MILLISECONDS)
                .subscribeOnIO()
                .observeOnMain()
                .doOnNext {
                    loadingDialog?.show()
                }
                .subscribe()
    }
}